﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace HungryCrowdLibrary.Data
{
    class MarketData
    {
        internal Market GetDetail(int marketId)
        {
            var market = new Market();
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HungryCrowd"].ConnectionString);
            conn.Open();

            using (var cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM dbo.Markets WHERE IsActive = 1 AND Id = @Id";
                cmd.Parameters.AddWithValue("@Id", marketId);
                cmd.Connection = conn;

                var reader = cmd.ExecuteReader();

                if (reader != null)
                    while (reader.Read())
                        market = LoadFromReader(reader);
            }
            return market;
        }

        internal List<Market> GetList(int locationId)
        {
            var markets = new List<Market>();
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HungryCrowd"].ConnectionString);
            conn.Open();

            using (var cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM dbo.Markets WHERE IsActive = 1 AND locationId = @locationId";
                cmd.Parameters.AddWithValue("@locationId", locationId);
                cmd.Connection = conn;

                var reader = cmd.ExecuteReader();

                if (reader != null)
                    while (reader.Read())
                        markets.Add(LoadFromReader(reader));
            }
            return markets;
        }

        internal Market LoadFromReader(IDataReader reader)
        {
            var market = new Market();

            market.Name = !string.IsNullOrWhiteSpace(reader["Name"].ToString()) ? reader["Name"].ToString() : string.Empty;
            market.Id = !string.IsNullOrWhiteSpace(reader["Id"].ToString()) ? int.Parse(reader["Id"].ToString()) : 0;
            market.IsActive = !string.IsNullOrWhiteSpace(reader["IsActive"].ToString()) ? bool.Parse(reader["IsActive"].ToString()) : false;
            market.LocationId = !string.IsNullOrWhiteSpace(reader["locationId"].ToString()) ? int.Parse(reader["locationId"].ToString()) : 0;

            return market;
        }

    }
}
